package org.zoomdev.zoom.validator.impl;

import org.zoomdev.zoom.common.utils.DateTimeUtils;
import org.zoomdev.zoom.validator.Validator;
import org.zoomdev.zoom.validator.annotations.DateFormat;

import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class DateFormatValidator implements Validator {
    private final DateTimeFormatter formatter;
    private final String formatPattern;

    private final String message;

    public DateFormatValidator(DateFormat annotation) {
        this.formatPattern = annotation.value();
        this.formatter = DateTimeUtils.ofPattern(formatPattern);
        this.message = annotation.message();
    }

    @Override
    public boolean isValid(Object value) {
        if (value == null) {
            return true;
        }
        try {
            // 处理字符串日期
            if (value instanceof CharSequence) {
                formatter.parse((CharSequence) value);
                return true;
            }
            return false;
        } catch (DateTimeParseException e) {
            return false;
        }
    }

    @Override
    public String getMessage() {
        return message;
    }
}
